package com.caesar.Net.TCP;

/**
 * @author caesar
 * @date 2025/7/22
 * @Description:
 * @apiNote
 */

import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) throws Exception{
        //1、主动连接服务器
        Socket socket = new Socket("192.168.39.60",8888);

        //2、在本地选择一个文件
        Scanner keyboard  = new Scanner(System.in);
        System.out.print("请输入你要上传的文件的完整路径名：");
        String filepath = keyboard.nextLine();//考虑到有的用户的文件夹名中包含空格，用nextLine()
        //D:\temp\img\dog.jpg
        File file =new File(filepath);
        String filename = file.getName();

        //3、给服务器发送文件名.扩展名，例如：dog.jpg
        OutputStream outputStream = socket.getOutputStream();
//        outputStream.write(filename.getBytes());//对方不方便  区分文件名和内容
        ObjectOutputStream oos = new ObjectOutputStream(outputStream);//对象输出流
        oos.writeUTF(filename);

        //4、先从本地读取文件内容，然后发送到服务器端
        FileInputStream fis = new FileInputStream(filepath);
        byte[] data = new byte[1024];
        while(true){
            int len = fis.read(data);
            if(len == -1){
                break;
            }
            //发送给服务器
            oos.write(data,0,len);
        }
        System.out.println("上传完毕！");

        //释放资源
        oos.close();
        outputStream.close();
        fis.close();
        keyboard.close();
        socket.close();
    }
}

